package com.nlp.server.service.impl;

import com.nlp.common.core.exception.ServiceException;
import com.nlp.common.core.web.pojo.AjaxResult;
import com.nlp.server.constant.ChatStatusConstant;
import com.nlp.server.mapper.ChatMessageMapper;
import com.nlp.server.mapper.UserChatMapper;
import com.nlp.server.pojo.dto.ChatDTO;
import com.nlp.server.pojo.entity.ChatBaseMessage;
import com.nlp.server.pojo.entity.ChatMessage;
import com.nlp.server.pojo.entity.ChatQueryParams;
import com.nlp.server.pojo.entity.UserChat;
import com.nlp.server.service.ChatService;
import com.nlp.server.utils.ChatUtils;
import com.nlp.server.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 会话服务层
 * @author shiliuyinzhen
 */
@Service
public class ChatServiceImpl implements ChatService {

    public final static Logger log = LoggerFactory.getLogger(ChatServiceImpl.class);

    @Autowired
    private ChatUtils chatUtils;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Autowired
    private UserChatMapper userChatMapper;

    @Override
    public AjaxResult createChat() {
        UserChat userChat = UserChat.builder()
                .userId(SecurityUtils.getUserId())
                .createTime(LocalDateTime.now())
                .build();
        if(userChatMapper.insertUserChat(userChat) > 0){
            AjaxResult ajaxResult = AjaxResult.success();
            HashMap<String,Long> map = new HashMap<>();
            map.put("chatId",userChat.getChatId());
            ajaxResult.put(AjaxResult.DATA_TAG, map);
            return ajaxResult;
        }
        return AjaxResult.error("创建回话失败");
    }

    /**
     * 查询问题
     *
     * @param chatDTO
     * @param sseEmitter
     * @return
     */
    @Override
    public void query(ChatDTO chatDTO,SseEmitter sseEmitter) {
        //查询是否有该会话
        //Todo redis缓存会话id
        //Todo 布隆过滤器、缓存预热
        Long chatId = chatDTO.getChatId();
        Long userId = SecurityUtils.getUserId();
        UserChat userChat = UserChat.builder()
                .userId(userId)
                .chatId(chatId)
                .build();
        if(userChatMapper.selectByCondition(userChat) == null){
                throw new ServiceException("无效的回话Id");
        }
        //获取历史会话记录
        ChatMessage chatMessage = ChatMessage.builder()
                .userId(userId)
                .chatId(chatId)
                .build();
        List<ChatBaseMessage> historyChat = chatMessageMapper.selectChatBaseMessage(chatMessage);
        ChatQueryParams chatQueryParams = ChatQueryParams.builder()
                .userId(userId.toString())
                .chatId(chatId.toString())
                .query(chatDTO.getQuery())
                .historyChat(historyChat)
                .status(ChatStatusConstant.NORMAL)
                .build();
        //计算花费的时间
        Double startTime = (double) System.currentTimeMillis();
        //与大模型交互获取结果
        String answer = chatUtils.sendQuestion(chatQueryParams,sseEmitter);
        Double endTime = (double) System.currentTimeMillis();
        //将结果存储到数据库
        ChatMessage chatMessage1 = ChatMessage.builder()
                .userId(userId)
                .chatId(chatId)
                .query(chatDTO.getQuery())
                .answer(answer)
                .costTime(endTime-startTime)
                .build();
        if(chatMessageMapper.insertChatMessage(chatMessage1) <= 0) {
            throw new ServiceException("会话记录保存失败");
        }
    }
}
